from typing import List

import pytest

from api.base_api import BaseUserApi, BaseReviewerApi, BaseTellerApi
from api.reviewer.reviewer_login_api import ReviewerLoginApi
from api.teller.teller_login_api import TellerLoginApi
from api.user.user_login_api import UserLoginApi
from common.db_util import DBUtil
from common.file_load import load_yaml_file
from common.logger import GetLogger
from config.environment import db_host
from paths_manager import common_yaml_path, db_yaml_path
from test_cases.purchase_financial_products_flow.test_purchase_fp_flow import TestPurchaseFpFlow
from test_cases.purchase_load_products_flow.test_purchase_lp_flow import TestPurchaseLpFlow


def pytest_collection_modifyitems(items: List["item"]):
    for item in items:
        item._nodeid = item._nodeid.encode('utf-8').decode("unicode-escape")


@pytest.fixture(scope='session', autouse=True)
def logger_init(worker_id):
    GetLogger.get_logger(worker_id).info('日志初始化成功')


@pytest.fixture(scope="session", autouse=True)
def user_login(worker_id):
    common_info = load_yaml_file(common_yaml_path)
    usernames = common_info['userName']
    passwords = common_info['userPassword']
    if worker_id == 'master':
        response = UserLoginApi(username=usernames[0], password=passwords[0]).send()
    else:
        # gw0,gw1,gw2,gw3
        # 提取worker_id中的数字
        index = int(worker_id[2:])
        response = UserLoginApi(username=usernames[index], password=passwords[index]).send()
    BaseUserApi.user_token = response.json()['token']

    # if worker_id == 'gw0' or worker_id == 'master':
    #     user_login_api = UserLoginApi(username="user1", password="123456")
    #     response = user_login_api.send()  # 这里返回的才是 requests.Response
    #     BaseUserApi.user_token = response.json()['token']  # 根据实际返回结构修改
    # elif worker_id == 'gw1':
    #     user_login_api = UserLoginApi(username="user2", password="123456")
    #     response = user_login_api.send()  # 这里返回的才是 requests.Response
    #     BaseUserApi.user_token = response.json()['token']  # 根据实际返回结构修改


@pytest.fixture(scope="session", autouse=True)
def reviewer_login(worker_id):
    common_info = load_yaml_file(common_yaml_path)
    reviewer_names = common_info['reviewerName']
    reviewer_passwords = common_info['reviewerPassword']
    if worker_id == 'master':
        response = ReviewerLoginApi(username=reviewer_names[0], password=reviewer_passwords[0]).send()
    else:
        # gw0,gw1,gw2,gw3
        # 提取worker_id中的数字
        index = int(worker_id[2:])
        response = ReviewerLoginApi(username=reviewer_names[index], password=reviewer_passwords[index]).send()
    BaseReviewerApi.reviewer_token = response.json()['token']

    # if worker_id == 'gw0' or worker_id == 'master':
    #     api = ReviewerLoginApi(username="shenhe1", password="123456")
    #     response = api.send()  # 这里返回的才是 requests.Response
    #     BaseReviewerApi.reviewer_token = response.json()['token']  # 根据实际返回结构修改
    # elif worker_id == 'gw1':
    #     api = ReviewerLoginApi(username="shenhe2", password="123456")
    #     response = api.send()  # 这里返回的才是 requests.Response
    #     BaseReviewerApi.reviewer_token = response.json()['token']  # 根据实际返回结构修改


@pytest.fixture(scope="session", autouse=True)
def teller_login(worker_id):
    common_info = load_yaml_file(common_yaml_path)
    teller_names = common_info['tellerName']
    teller_passwords = common_info['tellerPassword']
    if worker_id == 'master':
        response = TellerLoginApi(username=teller_names[0], password=teller_passwords[0]).send()
    else:
        # gw0,gw1,gw2,gw3
        # 提取worker_id中的数字
        index = int(worker_id[2:])
        response = TellerLoginApi(username=teller_names[index], password=teller_passwords[index]).send()
    BaseTellerApi.teller_token = response.json()['token']

    # if worker_id == 'gw0' or worker_id == 'master':
    #     api = TellerLoginApi(username="yewu1", password="123456")
    #     response = api.send()  # 这里返回的才是 requests.Response
    #     BaseTellerApi.teller_token = response.json()['token']  # 根据实际返回结构修改
    # elif worker_id == 'gw1':
    #     api = TellerLoginApi(username="yewu2", password="123456")
    #     response = api.send()  # 这里返回的才是 requests.Response
    #     BaseTellerApi.teller_token = response.json()['token']  # 根据实际返回结构修改


@pytest.fixture(scope='session', autouse=False)
def db_init():
    db_info = load_yaml_file(db_yaml_path)
    db_util = DBUtil(host=db_info['host'], user=db_info['username'], password=db_info['password'])
    yield db_util
    db_util.close()


# 在购买理财产品之前先把理财产品的库存初始化为1000
# 在购买之后将用户的余额重新设置回100w
# 最后清除掉这次的购买记录
@pytest.fixture(scope='class', autouse=False)
def fp_stock_init(db_init, fp_id=3, yonghu_id=3):
    db_init.update(f"UPDATE `licaicanpin` SET `licaicanpin_fenshu` = 1000 WHERE id = {fp_id}")
    yield
    db_init.update(f"UPDATE `yinhangka` SET `yinghangka_money` = 1000000 WHERE yonghu_id = {yonghu_id}")
    db_init.update(
        f"DELETE FROM `licaicanpin_goumai` WHERE id = (SELECT id FROM ( SELECT id FROM licaicanpin_goumai ORDER BY id DESC LIMIT 1) t)")


# 删除贷款商品
# 给银行卡id=4的每次更新为100w
@pytest.fixture(scope='class', autouse=False)
def lp_stock_init(db_init, yewurenyuan_id=1, bank_card_id=4):
    yield
    db_init.update(f"UPDATE `yinhangka` SET `yinghangka_money` = 1000000 WHERE id = {bank_card_id}")
    db_init.update(
        f"DELETE FROM daikuan WHERE id = (SELECT id FROM ( SELECT id FROM daikuan ORDER BY id DESC LIMIT 1) t)")
    db_init.update(f"truncate table `daikuan_goumai`")
